package com.ds.home.database.dao;

import com.ds.common.JDSConstants;
import com.ds.common.logging.Log;
import com.ds.common.logging.LogFactory;
import com.ds.home.database.BaseHibernateDAO;
import com.ds.home.database.vo.DeviceVO;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.NativeQuery;

import java.util.List;

/**
 * A data access object (DAO) providing persistence and search support for
 * DeviceVO entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 *
 * @author MyEclipse Persistence Tools
 * @see com.ds.home.database.BaseHibernateDAO
 */
public class DeviceDAO extends BaseHibernateDAO {
    private static final Log log = LogFactory.getLog(JDSConstants.CONFIG_KEY, DeviceDAO.class);
    // property constants
    public static final String SERIALNO = "serialno";
    public static final String MACADDRESS = "macaddress";
    public static final String BATCH = "batch";
    public static final String FACTORY = "factory";
    public static final String BINDINGACCOUNT = "bindingaccount";
    public static final String CHANNEL = "channel";
    public static final String SUBSYSCODE = "subsyscode";
    public static final String AREAID = "areaid";
    public static final String PLACEID = "placeid";
    public static final String DEVICETYPE = "devicetype";
    public static final String NAME = "name";
    public static final String BATTERY = "battery";
    public static final String LASTLOGINTIME = "lastlogintime";


    public void update(DeviceVO transientInstance) {
        synchronized (transientInstance.getDeviceid()) {
            log.debug("saving DeviceVO instance");
            try {
                this.getSession().getTransaction().begin();
                getSession().update(transientInstance);
                log.debug("save successful");
                getSession().getTransaction().commit();
            } catch (RuntimeException re) {
                log.error("save failed", re);
                throw re;
            } finally {
                close();
            }
        }

    }

    public  List<DeviceVO> loadByWhere(String where ){

        NativeQuery<DeviceVO> query = this.getSession().createNativeQuery("select *  from ha_device "+where.toLowerCase(), DeviceVO.class);
        List<DeviceVO>  volist= query.getResultList();
        return volist;
    }




    public void delete(DeviceVO persistentInstance) {
        log.debug("deleting DeviceVO instance");
        try {
            this.getSession().getTransaction().begin();
            getSession().delete(persistentInstance);
            getSession().getTransaction().commit();
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        } finally {
            close();
        }
    }

    public DeviceVO findById(String id) {
        log.debug("getting DeviceVO instance with id: " + id);
        DeviceVO instance = null;
        try {
            instance = (DeviceVO) getSession().get(
                    "com.ds.home.database.vo.DeviceVO", id);

        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        } finally {
            close();
        }
        return instance;
    }


    public List<DeviceVO> findDeviceByType(String factory,Integer type) {
        log.debug("finding DeviceVO instance by findDeviceByType");
        List<DeviceVO> results = null;
        try {
            Criteria criteria = getSession().createCriteria("com.ds.home.database.vo.DeviceVO");
            if (factory!=null && !factory.equals("")){
                criteria.add(Restrictions.eq(FACTORY, factory));
            }
            if (type!=null && !type.equals("")){
                criteria.add(Restrictions.eq(DEVICETYPE, type));
            }

            criteria.addOrder(Order.desc(LASTLOGINTIME));// 升序
            results= criteria.list();
            log.debug("find by example successful, result size: "
                    + results.size());

        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        } finally {
            close();
        }
        return results;
    }

    public List<DeviceVO> findByExample(DeviceVO instance) {
        log.debug("finding DeviceVO instance by example");
        List<DeviceVO> results = null;
        try {
            results = getSession()
                    .createCriteria("com.ds.home.database.vo.DeviceVO")
                    .addOrder(Order.asc("lastlogintime"))
                    .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());

        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        } finally {
            close();
        }
        return results;
    }

    public List<DeviceVO> findByProperty(String propertyName, Object value) {
        log.debug("finding DeviceVO instance with property: " + propertyName
                + ", value: " + value);
        List<DeviceVO> queryList = null;
        try {
            Criteria criteria = getSession().createCriteria("com.ds.home.database.vo.DeviceVO");
            criteria.add(Restrictions.eq(propertyName, value));
            criteria.addOrder(Order.desc(LASTLOGINTIME));// 升序
            queryList = criteria.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        } finally {
            close();
        }
        return queryList;
    }

    public List<DeviceVO> findBySerialno(Object serialno) {
        return findByProperty(SERIALNO, serialno);
    }

    public List<DeviceVO> findByAreaId(Object areaid) {
        return findByProperty(AREAID, areaid);
    }

    public List<DeviceVO> findByPlaceId(Object placeId) {
        return findByProperty(PLACEID, placeId);
    }


    public List<DeviceVO> findByMacaddress(Object macaddress) {
        return findByProperty(MACADDRESS, macaddress);
    }

    public List<DeviceVO> findByBatch(Object batch) {
        return findByProperty(BATCH, batch);
    }

    public List<DeviceVO> findByFactory(Object factory) {
        return findByProperty(FACTORY, factory);
    }

    public List<DeviceVO> findByBindingaccount(Object bindingaccount) {
        return findByProperty(BINDINGACCOUNT, bindingaccount);
    }

    public List<DeviceVO> findByChannel(Object channel) {
        return findByProperty(CHANNEL, channel);
    }

    public List<DeviceVO> findBySubsyscode(Object subsyscode) {
        return findByProperty(SUBSYSCODE, subsyscode);
    }


    public List<DeviceVO> findByName(Object name) {
        return findByProperty(NAME, name);
    }

    public List<DeviceVO> findByBattery(Object battery) {
        return findByProperty(BATTERY, battery);
    }

    public List<DeviceVO> findAll() {
        List<DeviceVO> queryList = null;
        log.debug("finding all DeviceVO instances");
        try {
            Criteria criteria = getSession().createCriteria("com.ds.home.database.vo.DeviceVO");
            criteria.addOrder(Order.desc(LASTLOGINTIME));// 升序
            queryList = criteria.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        } finally {
            close();
        }
        return queryList;

    }


    public void insert(DeviceVO instance) {
        log.debug("attaching dirty DeviceVO instance");
        try {
            this.getSession().getTransaction().begin();
            getSession().insert(instance);
            getSession().getTransaction().commit();
            log.debug("attach successful");
        } catch (Exception re) {
            log.error("attach failed", re);
            //throw re;
        } finally {
            close();
        }
    }


}